<template>
  <n-form :model="form" :rules="rules" ref="formRef" size="large">
    <n-form-item-row label="用户名" path="username">
      <n-input placeholder="请输入用户名" v-model:value="form.username"/>
    </n-form-item-row>
    <n-form-item-row label="密码" path="password">
      <n-input type="password" placeholder="请输入密码" v-model:value="form.password"
               @keydown.enter.prevent="handleLogin"/>
    </n-form-item-row>
  </n-form>
  <n-button type="primary" block secondary strong @click="handleLogin">
    登录
  </n-button>
</template>

<script setup lang="ts">


import {ref} from "vue";
import api from "@/api";
import {debounce, encrypt} from "@/utils";
import {useUserStore} from "@/sotre";
import router from "@/router";

const userStore = useUserStore()
const form = ref({
  username: '',
  password: '',
})
const formRef= ref()
const rules = ref({
  username: [{
    required: true,
    message: '请输入用户名',
    trigger: ['input']
  }],
  password: [{
    required: true,
    message: '请输入密码',
    trigger: ['input']
  }],
})

const handleLogin = debounce(() => {
  formRef.value.validate((error: any) => {
    if (!error) {
      api.auth.login({
        username:form.value.username,
        password:encrypt(form.value.password)
      }).then((res: any)=>{
        if(res&&res.data.code===0){
          window.$message.success("登录成功")
          userStore.setUserInfo(JSON.parse(res.data.data.userInfo))
          userStore.setToken(res.data.data.token)
          userStore.setRefreshToken(res.data.data.refreshToken)
          router.push({path:'/workbench'})
        }
      })
    }
  })

},1000)
</script>

<style scoped>

</style>
